package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"prodct/cache"
	"prodct/models"
)

type ProdctController struct {
	beego.Controller
}

func (c *ProdctController) Add() {
	name := c.GetString("name")
	price := c.GetString("price")
	description := c.GetString("description")
	stock := c.GetString("stock")
	var pro models.Prodct
	pro.Name = name
	pro.Price = price
	pro.Description = description
	pro.Stock = stock
	if pro.Add() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := pro.List()
	keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "list", keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *ProdctController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price := c.GetString("price")
	description := c.GetString("description")
	stock := c.GetString("stock")
	var pro models.Prodct
	pro.ID = uint(id)
	pro.Name = name
	pro.Price = price
	pro.Description = description
	pro.Stock = stock
	if pro.Update() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := pro.List()
	keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "list", keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *ProdctController) Del() { //删除
	id, _ := c.GetInt("id")
	var pro models.Prodct
	pro.ID = uint(id)
	if pro.Del() != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	key, _ := pro.List()
	keys, _ := json.Marshal(key)
	cache.Rdb.Set(cache.Ctx, "list", keys, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}

func (c *ProdctController) List() {
	get, _ := cache.Rdb.Get(cache.Ctx, "redis_list").Result()
	var pro []*models.Prodct
	if get == "" {
		models.DB.Find(&pro)
		redisdata, _ := json.Marshal(pro)
		cache.Rdb.Set(cache.Ctx, "redis_list", redisdata, 0)
	} else {
		json.Unmarshal([]byte(get), &pro)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 500,
		"msg":  "查询成功",
		"data": pro,
	}
	c.ServeJSON()
	return
}
